﻿
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.Text;

using Swaf;
using Swaf.BizObj;
using Swaf.Gui;
using Swaf.Security;

namespace eCom.Gui
{
	public class eComSalesOrderDeliveryOptionsBizProc : BaseBusinessProcess
	{
		//When true, this triggers the bizrule to not use its cache 
		protected bool m_forceGetDeliveryOptions = false;
		protected bool m_setDeliveryErrorsAlready = false;
		protected bool m_triggerCheckShipping = false;
		protected int m_getCount = 0;
		protected bool m_needsShipping = false;
		public eComSalesOrderDeliveryOptionsBizProc(ActiveBizProc procState) : base(procState) { }

		protected override void setupRuleNames()
		{
			m_getBizObjListRule = "getSalesOrderDeliveryOptions";
			m_updateBizObjRule = "updateSalesOrderDeliveryOption";
		}

		public override Privileges CurrentEditPrivilege
		{
			get { return Privileges.Delete; }
		}

		protected override object[] getBizObjListRuleParameters(object parentId, IBizObj filterSort)
		{
			if (m_forceGetDeliveryOptions)
				m_setDeliveryErrorsAlready = false;
			return new object[] { m_procState.get("orderInfo"), m_forceGetDeliveryOptions };
		}

		protected override object[] getUpdateBizRuleParameters(IBizObj deliveryControl)
		{
			return new object[] { m_procState.get("orderInfo"), deliveryControl.get("selected") };
		}

		protected override IBizObjList getListFromBizRuleResults(IResults rc)
		{
			IBizObj deliveryOptions = rc.CallResults as IBizObj;
			IBizObjList options = null;
			if (deliveryOptions != null)
			{
				bool enabled = (bool)deliveryOptions.get("enable");
				if (enabled)
				{
					m_needsShipping = true;
					options = deliveryOptions.get("options") as IBizObjList;
					if (m_triggerCheckShipping && ++m_getCount == 2 && !m_setDeliveryErrorsAlready)
					{
						IBizObjList errors = deliveryOptions.get("errors") as IBizObjList;
						foreach (IBizObj error in errors)
							m_procState.BPC.Messenger.add((string)error.get("errorMessageId"), (Swaf.Container.FlexiMap)error.get("errorInfo"));
						m_setDeliveryErrorsAlready = true;
					}
				}
				else
					base.setChildTypeVisibility(BizProcWidgetType.disp, false);
			}
			return options;
		}


		protected override void getCurrentBizObj()
		{
			if (State.InProgressAddBizObj == null)
				State.InProgressAddBizObj = App.bizObjMgr.create("eComDeliveryControl");
			m_currentBizObj = State.InProgressAddBizObj;
			IBizObj order = m_procState.get("orderInfo") as IBizObj;
			if (order != null)
			{
				m_currentBizObj.put("order", order);
				if (SourceBizObjs != null)
					foreach(IBizObj sb in SourceBizObjs)
						if (((IComparable)sb.get("provider.id")).CompareTo(order.get("delivery.provider.id")) == 0 &&
							((IComparable)sb.get("deliveryMethodName")).CompareTo(order.get("delivery.deliveryMethodName")) == 0)
						{
							m_currentBizObj.put("selected", sb);
							if (((IComparable)sb.get("total")).CompareTo(order.get("delivery.total")) != 0)
							{
								order.put("delivery", sb);
								IResults rc = App.ruleMgr.execute("updateSalesOrder", order);
								rc = App.ruleMgr.execute(m_updateBizObjRule, order, sb);
							}
						}
			}
			m_retrievedCurrentBizObj = true;
		}

		public override void showData(ForceLevel level)
		{
			getCurrentBizObj();
			base.showData(level);
		}

		public void setupDeliveryOptions()
		{
			m_triggerCheckShipping = true;
			clearRetrievedData();
			getCurrentBizObj();
			m_forceGetDeliveryOptions = true;
			getBizObjList();
			m_forceGetDeliveryOptions = false;
			if ((CurrentBizObj == null || CurrentBizObj.get("selected.id")==null) && SourceBizObjs != null && SourceBizObjs.Count > 0)
				selectBizObj(SourceBizObjs[SourceBizObjs.Count - 1].KeyValue, null);

		}

		public override IBizObj selectBizObj(object keyValue, object source)
		{
			IBizObj selectedDelivery = null;
			if (SourceBizObjs != null)
			{
				selectedDelivery = SourceBizObjs.search(SourceBizObjs.objectType.KeyFieldNames, SourceBizObjs.objectType.convertValueToKeyType(keyValue.ToString()));
				if (selectedDelivery != null)
				{
					CurrentBizObj.put("selected", selectedDelivery);
					IBizObj order = m_procState.get("orderInfo") as IBizObj;
					if (order != null)
					{
						order.put("delivery.id", selectedDelivery.get("id"));
						IResults rc = App.ruleMgr.execute("updateSalesOrder", order);
						rc = App.ruleMgr.execute(m_updateBizObjRule, order, selectedDelivery);
					}
					base.forceParentBizProcUpdates();
				}
			}
			return selectedDelivery;
		}

		protected override void showBizObjListInDisplay(IBizObjListDisplay listDisp, IBizObjCursor cur)
		{
			listDisp.showBizObjs(this, cur);
			if (listDisp.DrivenByBizProc)
				listDisp.SelectedBizObjKeyValue = CurrentBizObj.get("selected.id");
		}

		public void validateDeliveryOptions()
		{
			if (m_needsShipping)
			{
				IBizObj order = m_procState.get("orderInfo") as IBizObj;
				if (order != null)
				{
					IBizObj orderDelivery = (IBizObj)order.get("delivery");
					if (orderDelivery.get("id") == null)
					{
						IBizObj wizardInfo = m_procState.get("info", false) as IBizObj;
						if (wizardInfo != null)
							wizardInfo.put("stepCompleted", false);
						m_procState.BPC.Messenger.add("Error-MustPickShippingMethod", null);
					}
				}
			}
		}

		public override IResults updateBizObj(IBizObj obj)
		{
			if(m_needsShipping)
				return base.updateBizObj(obj);
			return null;
		}

		protected override bool validateBizObj(IBizObj obj)
		{
			if (obj != null)
				obj.validate();
			return true;
		}

		protected override bool shouldCallGetBizObjListRule(object parentBizObjId)
		{
			return true;
		}

		protected override void setupActions()
		{
			base.setupActions();
			Actions.addAction(new GenericAction("SetupDeliveryOptions", true, setupDeliveryOptions, this));
			Actions.addAction(new GenericAction("ValidateDeliveryOptions", true, validateDeliveryOptions, this));
		}
	}
}
